package org.cid54.jshopper.controller;

import javax.servlet.http.HttpServletRequest;
import org.cid54.jshopper.model.User;
import org.cid54.jshopper.service.UserAndGroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

/**
 *
 * @author fgo
 */
@Controller
public class AuthenticationController {

    @Autowired
    private UserAndGroupService userAndGroupService;

    @ModelAttribute("user")
    public User getUser() {
        return new User();
    }

    @RequestMapping(value = "logout", method = RequestMethod.GET)
    public String doLogout(HttpServletRequest request) {

        request.getSession().invalidate();

        return "redirect:/mvc/home";
    }

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public ModelAndView doGet() {
        ModelAndView mav = new ModelAndView("login");

        return mav;
    }

    @RequestMapping(value = "login", method = RequestMethod.POST)
    public String doPost(User user, HttpServletRequest request) {

        if (this.userAndGroupService.authenticate(user.getName(), user.getPassword())) {

            user = this.userAndGroupService.getUserByUserName(user.getName());

            request.getSession().setAttribute("userName", user.getName());
            request.getSession().setAttribute("admin", user.isAdmin());

            return "redirect:/";
        } else {
            return "redirect:/mvc/login";
        }
    }
}
